package com.ruoyi.encrypt.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SM4;
import com.ruoyi.core.exception.RunException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author wanghao 913351190@qq.com
 * @create 2022/3/31 9:10
 */
@Slf4j
public abstract class SM4Util {

    //默认SM4加解密密钥
    private static final String SM4_KEY = "7f862c7qw1bc441e";


    /**
     * SM4加密(PKCS7Padding、Base64)
     *
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        return encrypt(SM4_KEY, content);
    }

    /**
     * SM4解密(PKCS7Padding、Base64)
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        return decrypt(SM4_KEY, content);
    }


    /**
     * SM4加密(PKCS7Padding、Base64)(使用对方密钥加密)
     *
     * @param content
     * @return
     */
    public static String encrypt(String key, String content) {
        if (StringUtils.isEmpty(key)) {
            throw new RunException("加密密钥为空");
        }
        if (StringUtils.isEmpty(content)) {
            throw new RunException("加密报文为空");
        }
        try {
            SM4 sm4 = new SM4("ECB", "PKCS7Padding", key.getBytes(StandardCharsets.UTF_8));
            byte[] encrypt = sm4.encrypt(content);
            return Base64.encode(encrypt);
        } catch (Throwable e) {
            log.error("加密失败", e);
            throw new RunException("加密失败");
        }
    }


    /**
     * SM4解密(PKCS7Padding、Base64)（使用自己密钥解密）
     *
     * @param content
     * @return
     */
    public static String decrypt(String key, String content) {
        if (StringUtils.isEmpty(key)) {
            throw new RunException("加密密钥为空");
        }
        if (StringUtils.isEmpty(content)) {
            throw new RunException("加密报文为空");
        }
        try {
            SM4 sm4 = new SM4("ECB", "PKCS7Padding", SM4_KEY.getBytes(StandardCharsets.UTF_8));
            byte[] decode = Base64.decode(content);
            return StrUtil.utf8Str(sm4.decrypt(decode));
        } catch (Throwable e) {
            log.error("解密失败", e);
            throw new RunException("解密失败");
        }
    }


}
